package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.apis.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;
    
    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 自媒体文章审核
     *
     * @param id 自媒体文章id
     */
    @Override
    @Async
    public void autoScanWmNews(Integer id) {
        // 1.查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        // 2.文章文本审核
        if (wmNews == null) {
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章不存在");
        }
        // 获取文章内容和图片列表返回map
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            Map<String, Object> resultMap = getContentAndImagesMap(wmNews);
            // 审核自管理的敏感词汇
            Boolean sensitiveFlag = handleSensitiveScan(wmNews, resultMap.get("text").toString());
            if (!sensitiveFlag) {
                return;
            }
            // 审核文本
            Boolean textScanFlag =  handleTextScan(wmNews, resultMap.get("text").toString());
            if (!textScanFlag) {
                return;
            }
            // 3.审核图片
            Boolean imageScanFlag = handleImageScan(wmNews, (List<String>) resultMap.get("images"));
            if (!imageScanFlag) {
                return;
            }
            // 4.调用文章feign接口保存三剑客
            ResponseResult responseResult = saveAppArticle(wmNews);
            if (!responseResult.getCode().equals(200)) {
                throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存app端相关文章数据失败");
            }
            // 5.回填article_id
            wmNews.setArticleId((Long) responseResult.getData());
            updateWmNews(wmNews,"审核成功", WmNews.Status.PUBLISHED.getCode());
        }
    }

    /**
     * 自管理敏感词汇审核
     * @param wmNews    自媒体文章
     * @param text      待审核的文本
     * @return          Boolean
     */
    private Boolean handleSensitiveScan(WmNews wmNews, String text) {
        Boolean flag = true;
        if (text.length() == 0) {
            return flag;
        }
        List<String> sensitives = wmSensitiveMapper.selectList(null)
                .stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        SensitiveWordUtil.initMap(sensitives);
        Map<String, Integer> matchMap = SensitiveWordUtil.matchWords(text);
        if (matchMap.size() > 0) {
            flag = false;
            updateWmNews(wmNews, "当前文章中存在违规内容", WmNews.Status.FAIL.getCode());
        }
        return flag;
    }

    /**
     * 保存三剑客
     * @param wmNews    自媒体文章
     * @return          ResponseResult
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {
        // 数据封装
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, dto);
        //文章的布局
        dto.setLayout(wmNews.getType());
        //频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if(wmChannel != null){
            dto.setChannelName(wmChannel.getName());
        }

        //作者
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(wmUser != null){
            dto.setAuthorName(wmUser.getName());
        }

        //设置文章id
        if(wmNews.getArticleId() != null){
            dto.setId(wmNews.getArticleId());
        }
        dto.setCreatedTime(new Date());

        ResponseResult responseResult = articleClient.save(dto);
        return responseResult;
    }

    /**
     * 图片审核
     * @param wmNews    自媒体文章
     * @param images    图片url列表
     * @return          Boolean
     */
    private Boolean handleImageScan(WmNews wmNews, List<String> images) {
        Boolean flag = true;
        if (images == null || images.size() == 0) {
            return flag;
        }
        List<byte[]> imageBytes = new ArrayList<>();
        images = images.stream().distinct().collect(Collectors.toList());
        try {
            for (String image : images) {
                byte[] bytes = fileStorageService.downLoadFile(image);
                ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                BufferedImage bufferImage = ImageIO.read(in);
                String result = tess4jClient.doOCR(bufferImage);
                Boolean sensitiveFlag = handleSensitiveScan(wmNews, result);
                if (!sensitiveFlag) {
                    return sensitiveFlag;
                }
                imageBytes.add(bytes);
            }
            Map map = greenImageScan.imageScan(imageBytes);
            if ("block".equals(map.get("suggestion"))) {
                flag = false;
                updateWmNews(wmNews, "当前文章图片存在违规信息", WmNews.Status.FAIL.getCode());
            }
            if ("review".equals(map.get("suggestion"))) {
                flag = false;
                updateWmNews(wmNews, "当前文章图片存在不确定信息", WmNews.Status.ADMIN_AUTH.getCode());
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 文本审核
     * @param wmNews    自媒体文章
     * @param text      要审核的文本
     * @return          Boolean
     */
    private Boolean handleTextScan(WmNews wmNews, String text) {
        Boolean flag = true;
        if (text.length() == 0) {
            return flag;
        }
        try {
            Map map = greenTextScan.greeTextScan(text);
            if ("block".equals(map.get("suggestion"))) {
                flag = false;
                updateWmNews(wmNews, "当前文章内容存在违规词汇", WmNews.Status.FAIL.getCode());
            }
            if ("review".equals(map.get("suggestion"))) {
                flag = false;
                updateWmNews(wmNews, "当前文章内容存在不确定词汇", WmNews.Status.ADMIN_AUTH.getCode());
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    private void updateWmNews(WmNews wmNews, String message, Short status) {
        wmNews.setReason(message);
        wmNews.setStatus(status);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 获取文章内容和图片url列表
     * @param wmNews    文章
     * @return          Map
     */
    private Map<String, Object> getContentAndImagesMap(WmNews wmNews) {
        StringBuilder sb = new StringBuilder();
        sb.append(wmNews.getTitle());
        sb.append(wmNews.getLabels());
        List<String> images = new ArrayList<>();
        // 1.从自媒体文章中提取出内容和内容图片
        String content = wmNews.getContent();
        if (StringUtils.isNotEmpty(content)) {
            List<Map> maps = JSONArray.parseArray(content, Map.class);
            for (Map map : maps) {
                if ("text".equals(map.get("type"))) {
                    sb.append(map.get("value"));
                }
                if ("image".equals(map.get("type"))) {
                    images.add((String) map.get("value"));
                }
            }
        }
        // 2.获取封面图片
        String imageUrls = wmNews.getImages();
        if (StringUtils.isNotEmpty(imageUrls)) {
            String[] split = imageUrls.split(",");
            images.addAll(Arrays.asList(split));
        }
        // 3.封装数据
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("text", sb.toString());
        resultMap.put("images", images);
        return resultMap;
    }
}
